package me.zhengjie.modules.sync.processing;

import com.alibaba.fastjson.JSON;
import com.qiaofang.applet.common.constant.SyncTypeEnum;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.repository.EmployeeReportRepository;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.property.domain.SyncDataQueue;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.sync.ProcessingBase;
import me.zhengjie.utils.ImageUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/*
* 经纪人数据处理
* */
@Slf4j
@Service
public class EmployeeSyncProcessing extends ProcessingBase {

    public EmployeeSyncProcessing(){
        setDataType(SyncTypeEnum.EMP.getSyncType());
    }

    @Autowired
    EmployeeService employeeService;

    @Autowired
    private EmployeeReportRepository employeeReportRepository;

    @Override
    protected void processing(SyncDataQueue syncDataQueue) {
        String batchContent=syncDataQueue.getBatchContent();
        List<Employee> list= JSON.parseArray(batchContent, Employee.class);
        if(null==list){
            log.info("processing District is null");
            return;
        }
        list.stream().forEach(item->{
            saveEmployee(item,syncDataQueue);
        });
    }

    private void saveEmployee(Employee item,SyncDataQueue syncDataQueue){
        String employeeUniqueUuid=syncDataQueue.getCompanyUuid()+"_"+item.getEmployeeUuid();
        Employee employee= employeeService.findByEmployeeUniqueUuid(employeeUniqueUuid);
        if(!Objects.isNull(item.getDeleted()) && item.getDeleted()){
            if (!Objects.isNull(employee)) {
                employeeService.deleteById(employee.getId());
                employeeReportRepository.deleteByEmployeeUniqueUuid(employeeUniqueUuid);
            }
            return;
        }
        //离职员工：新数据不导入，旧数据删除处理
        if ("离职".equals(item.getStatus())){
            if (!Objects.isNull(employee)){
                employeeService.deleteById(employee.getId());
                employeeReportRepository.deleteByEmployeeUniqueUuid(employeeUniqueUuid);
            }
            return;
        }
        if(Objects.isNull(employee)){
            employee=new Employee();
            employee.setRecommend(false);
            employee.setRecommendDescribe("");
        }
        //复制属性
        String[] ignoreProperties=new String[] {"id","createBy","updateBy","createTime","updateTime","hotStatus","recommend","remarkList","labelUuidList", "inspectionCount", "tradeCount", "focusByCount", "receptionCount"};
        BeanUtils.copyProperties(item,employee,ignoreProperties);
        employee.setEmployeeName(item.getName());
        employee.setMobilePhone(item.getCellphone());
        employee.setCompanyUuid(syncDataQueue.getCompanyUuid());
        employee.setCityCode(syncDataQueue.getCityCode());
        employee.setCorporationCode(syncDataQueue.getCorporationCode());
        employee.setUpdateTime(new Date());
        employee.setEmployeeUniqueUuid(employeeUniqueUuid);
        employee.setRelationUpdate(true);
        employee.setLastSyncDate(new Date(System.currentTimeMillis() - DateUtil.DAY_MILLISECONDS));
        replaceDomain(employee);
        try {
            employeeService.save(employee);
        } catch (Exception e) {
            log.error("saveEmployee error",e);
            //记录错误日志
            this.saveErrorLog(JSON.toJSONString(employee),e.getMessage(),syncDataQueue);
        }
    }

    //替换域名
    private void replaceDomain(Employee employee){
        String photoURL = employee.getPhotoUrl();
        if(StringUtils.isEmpty(employee.getPhotoUrl())){
            return;
        }
        if ((photoURL.startsWith(ImageUtil.HTTP) || photoURL.startsWith(ImageUtil.HTTPS)) && photoURL.contains(ImageUtil.DISCARD_IMAGE_URL)) {
            photoURL = StringUtils.replace(photoURL, ImageUtil.DISCARD_IMAGE_URL, ImageUtil.IMAGE_URL);
        } else if (photoURL.startsWith("//")){
            photoURL = ImageUtil.HTTPS_NO_SLASH + photoURL;
        }else {
            photoURL = ImageUtil.HTTPS + ImageUtil.IMAGE_URL + "/" + photoURL;
        }
        employee.setPhotoUrl(photoURL);
    }
}
